<template>
  <div class="short-answer-problem-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="$router.back()" icon="ArrowLeft" class="back-btn">返回</el-button>
        <div class="header-info">
          <h2>{{ problem?.title || '简答题' }}</h2>
          <div class="problem-meta">
            <el-tag type="success" size="small">简答题</el-tag>
            <el-tag v-if="problem?.difficulty" :type="getDifficultyTagType(problem.difficulty)" size="small">
              {{ getDifficultyText(problem.difficulty) }}
            </el-tag>
            <span v-if="problem?.points" class="points">{{ problem.points }}分</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="submitAnswer" :disabled="!shortAnswer.trim()" :loading="submitting">
          <el-icon><Upload /></el-icon>
          提交答案
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div v-if="problem" class="main-content">
      <div class="problem-container">
        <!-- 题目描述 -->
        <div class="problem-description">
          <h3>题目描述</h3>
          <div class="description-content" v-html="formatDescription(problem.description)"></div>
          
          <!-- 输入格式 -->
          <div v-if="problem.input_format" class="input-format-section">
            <h4>输入格式：</h4>
            <pre class="format-content">{{ problem.input_format }}</pre>
          </div>
          
          <!-- 输出格式 -->
          <div v-if="problem.output_format" class="output-format-section">
            <h4>输出格式：</h4>
            <pre class="format-content">{{ problem.output_format }}</pre>
          </div>
        </div>

        <!-- 答案输入 -->
        <div class="answer-section">
          <h3>请输入您的答案：</h3>
          <div class="answer-input-container">
            <el-input
              v-model="shortAnswer"
              type="textarea"
              :rows="8"
              placeholder="请详细描述您的答案..."
              show-word-limit
              maxlength="1000"
              class="answer-textarea"
            />
            <div class="answer-tips">
              <el-icon><InfoFilled /></el-icon>
              <span>提示：请详细描述您的答案，系统会根据关键词匹配进行评分</span>
            </div>
          </div>
        </div>

        <!-- 提交结果 -->
        <div v-if="submitResult" class="submit-result">
          <div class="result-header">
            <h3>提交结果</h3>
          </div>
          <div class="result-content" :class="submitResult.status">
            <div class="result-status">
              <el-icon v-if="submitResult.status === 'AC'"><CircleCheck /></el-icon>
              <el-icon v-else-if="submitResult.status === 'WA'"><CircleClose /></el-icon>
              <el-icon v-else><Warning /></el-icon>
              {{ getResultStatusText(submitResult.status) }}
            </div>
            <div class="result-details">
              <p>您的答案：{{ shortAnswer }}</p>
              <p v-if="submitResult.correct_answer">参考答案：{{ submitResult.correct_answer }}</p>
              <p>得分：{{ submitResult.score }}/{{ submitResult.max_score }}</p>
              <p v-if="submitResult.details" class="score-details">{{ submitResult.details }}</p>
              
              <!-- 关键词匹配详情 -->
              <div v-if="submitResult.matchDetails && submitResult.matchDetails.length > 0" class="match-details">
                <h4>关键词匹配详情：</h4>
                <div class="keyword-list">
                  <span 
                    v-for="detail in submitResult.matchDetails" 
                    :key="detail"
                    class="keyword-item"
                    :class="{
                      'match-correct': detail.startsWith('✓'),
                      'match-partial': detail.startsWith('~'),
                      'match-missing': detail.startsWith('✗')
                    }"
                  >
                    {{ detail }}
                  </span>
                </div>
                <div class="match-legend">
                  <span class="legend-item">
                    <span class="legend-icon match-correct">✓</span> 完全匹配
                  </span>
                  <span class="legend-item">
                    <span class="legend-icon match-partial">~</span> 部分匹配
                  </span>
                  <span class="legend-item">
                    <span class="legend-icon match-missing">✗</span> 未匹配
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <div v-loading="true" style="height: 200px;"></div>
      <p>加载题目中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="题目不存在或加载失败" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleCheck, CircleClose, Warning, InfoFilled } from '@element-plus/icons-vue'
import { problemsApi } from '@/api/problems'
import type { Problem } from '@/types'

const route = useRoute()
const router = useRouter()

const problem = ref<Problem | null>(null)
const loading = ref(true)
const submitting = ref(false)
const shortAnswer = ref('')
const submitResult = ref<any>(null)

// 加载题目
const loadProblem = async () => {
  try {
    loading.value = true
    const response = await problemsApi.getProblem(Number(route.params.id))
    problem.value = response
    
    // 检查题目类型
    if (problem.value && problem.value.type !== 'short') {
      ElMessage.error('此页面仅适用于简答题')
      router.back()
      return
    }
  } catch (error: any) {
    console.error('加载题目失败:', error)
    ElMessage.error('加载题目失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 提交答案
const submitAnswer = async () => {
  if (!shortAnswer.value.trim()) {
    ElMessage.warning('请先输入答案')
    return
  }

  try {
    submitting.value = true
    
    // 智能关键词匹配评分
    const answerLower = shortAnswer.value.toLowerCase().trim()
    const correctAnswerLower = problem.value?.answer?.toLowerCase().trim() || ''
    
    const scoreResult = calculateKeywordScore(answerLower, correctAnswerLower, problem.value?.points || 10)
    
    const score = scoreResult.score
    const isCorrect = scoreResult.isCorrect
    
    submitResult.value = {
      status: isCorrect ? 'AC' : 'WA',
      score: score,
      max_score: problem.value?.points || 10,
      correct_answer: problem.value?.answer,
      details: scoreResult.details,
      matchDetails: scoreResult.matchDetails
    }
    
    if (isCorrect) {
      ElMessage.success('回答正确！')
    } else {
      ElMessage.warning('回答部分正确，请查看评分详情')
    }
  } catch (error: any) {
    console.error('提交答案失败:', error)
    ElMessage.error('提交答案失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 智能关键词评分函数
const calculateKeywordScore = (userAnswer: string, correctAnswer: string, maxScore: number) => {
  // 如果完全匹配，给满分
  if (userAnswer === correctAnswer) {
    return { score: maxScore, isCorrect: true, details: '完全正确' }
  }
  
  // 移除标点符号和多余空格
  const cleanUser = userAnswer.replace(/[，。！？；：""''()（）【】]/g, ' ').replace(/\s+/g, ' ')
  const cleanCorrect = correctAnswer.replace(/[，。！？；：""''()（）【】]/g, ' ').replace(/\s+/g, ' ')
  
  // 提取关键词（排除常见停用词）
  const stopWords = ['的', '了', '在', '是', '有', '和', '或', '但', '因为', '所以', '如果', '那么', '这样', '那样', '这个', '那个', '它们', '我们', '他们', '她们', '一个', '一些', '一种', '主要', '重要', '基本', '一般', '通常', '可以', '能够', '应该', '必须', '可能', '也许', '比较', '非常', '特别', '尤其', 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'can', 'this', 'that', 'these', 'those']
  
  const extractKeywords = (text: string) => {
    return text.split(/\s+/)
      .filter(word => word.length > 1)
      .filter(word => !stopWords.includes(word))
      .filter(word => !/^\d+$/.test(word)) // 排除纯数字
  }
  
  const correctKeywords = extractKeywords(cleanCorrect)
  const userKeywords = extractKeywords(cleanUser)
  
  if (correctKeywords.length === 0) {
    // 如果没有关键词，使用字符串相似度
    const similarity = calculateStringSimilarity(cleanUser, cleanCorrect)
    const score = Math.floor(similarity * maxScore)
    return { 
      score, 
      isCorrect: similarity >= 0.8, 
      details: `相似度: ${Math.round(similarity * 100)}%` 
    }
  }
  
  // 计算关键词匹配情况
  let matchedCount = 0
  let partialMatchCount = 0
  const matchDetails: string[] = []
  
  for (const keyword of correctKeywords) {
    if (userKeywords.includes(keyword)) {
      matchedCount++
      matchDetails.push(`✓ ${keyword}`)
    } else {
      // 检查部分匹配（包含关系）
      const partialMatch = userKeywords.find(userWord => 
        userWord.includes(keyword) || keyword.includes(userWord)
      )
      if (partialMatch) {
        partialMatchCount++
        matchDetails.push(`~ ${keyword}`)
      } else {
        matchDetails.push(`✗ ${keyword}`)
      }
    }
  }
  
  // 计算得分
  const exactMatchRate = matchedCount / correctKeywords.length
  const partialMatchRate = partialMatchCount / correctKeywords.length
  const totalMatchRate = exactMatchRate + (partialMatchRate * 0.5)
  
  // 奖励额外的相关词汇
  const bonusWords = userKeywords.filter(word => 
    !correctKeywords.includes(word) && 
    correctKeywords.some(cw => word.includes(cw) || cw.includes(word))
  )
  const bonusRate = Math.min(bonusWords.length * 0.1, 0.2) // 最多20%奖励
  
  const finalRate = Math.min(totalMatchRate + bonusRate, 1.0)
  const score = Math.floor(finalRate * maxScore)
  const isCorrect = finalRate >= 0.7 // 70%以上认为正确
  
  return {
    score,
    isCorrect,
    details: `关键词匹配: ${matchedCount}/${correctKeywords.length} (${Math.round(exactMatchRate * 100)}%)`,
    matchDetails
  }
}

// 字符串相似度计算（使用编辑距离）
const calculateStringSimilarity = (str1: string, str2: string): number => {
  const len1 = str1.length
  const len2 = str2.length
  
  if (len1 === 0) return len2 === 0 ? 1 : 0
  if (len2 === 0) return 0
  
  const dp: number[][] = Array(len1 + 1).fill(null).map(() => Array(len2 + 1).fill(0))
  
  for (let i = 0; i <= len1; i++) dp[i][0] = i
  for (let j = 0; j <= len2; j++) dp[0][j] = j
  
  for (let i = 1; i <= len1; i++) {
    for (let j = 1; j <= len2; j++) {
      if (str1[i - 1] === str2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1]
      } else {
        dp[i][j] = Math.min(
          dp[i - 1][j] + 1,     // 删除
          dp[i][j - 1] + 1,     // 插入
          dp[i - 1][j - 1] + 1  // 替换
        )
      }
    }
  }
  
  const maxLen = Math.max(len1, len2)
  return (maxLen - dp[len1][len2]) / maxLen
}

// 格式化题目描述
const formatDescription = (description: string) => {
  return description.replace(/\n/g, '<br>')
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty: string) => {
  const typeMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const textMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return textMap[difficulty] || difficulty
}

// 获取结果状态文本
const getResultStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    AC: '答案正确',
    WA: '答案错误',
    CE: '编译错误',
    TLE: '时间超限',
    MLE: '内存超限',
    RE: '运行时错误',
    PE: '格式错误'
  }
  return statusMap[status] || status
}

onMounted(() => {
  loadProblem()
})
</script>

<style scoped lang="scss">
.short-answer-problem-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 20px;

    .back-btn {
      background: linear-gradient(45deg, #667eea, #764ba2);
      border: none;
      color: white;
      border-radius: 8px;
      padding: 10px 15px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
      }
    }

    .header-info {
      h2 {
        margin: 0 0 8px 0;
        color: #2c3e50;
        font-size: 1.8rem;
        font-weight: 600;
      }

      .problem-meta {
        display: flex;
        gap: 10px;
        align-items: center;

        .points {
          font-weight: 600;
          color: #e74c3c;
          background: rgba(231, 76, 60, 0.1);
          padding: 4px 8px;
          border-radius: 4px;
        }
      }
    }
  }

  .header-right {
    .el-button {
      background: linear-gradient(45deg, #667eea, #764ba2);
      border: none;
      border-radius: 8px;
      padding: 12px 24px;
      font-weight: 600;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
      }

      &:disabled {
        background: #ccc;
        transform: none;
        box-shadow: none;
      }
    }
  }
}

.main-content {
  .problem-container {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .problem-description {
      margin-bottom: 30px;

      h3 {
        color: #2c3e50;
        margin-bottom: 15px;
        font-size: 1.4rem;
        font-weight: 600;
      }

      .description-content {
        color: #34495e;
        line-height: 1.6;
        font-size: 1.1rem;
      }
    }

    .answer-section {
      margin-bottom: 30px;

      h3 {
        color: #2c3e50;
        margin-bottom: 20px;
        font-size: 1.3rem;
        font-weight: 600;
      }

      .answer-input-container {
        .answer-textarea {
          margin-bottom: 15px;

          :deep(.el-textarea__inner) {
            border-radius: 10px;
            border: 2px solid #e1e8ed;
            transition: all 0.3s ease;
            background: white;
            font-size: 1.1rem;
            line-height: 1.6;
            padding: 15px 20px;
            resize: vertical;
            min-height: 200px;

            &:hover {
              border-color: #667eea;
              box-shadow: 0 2px 10px rgba(102, 126, 234, 0.2);
            }

            &:focus {
              border-color: #667eea;
              box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
            }
          }
        }

        .answer-tips {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #666;
          font-size: 0.9rem;
          padding: 10px 15px;
          background: rgba(102, 126, 234, 0.1);
          border-radius: 8px;
          border-left: 4px solid #667eea;

          .el-icon {
            color: #667eea;
            font-size: 1rem;
          }
        }
      }
    }

    .submit-result {
      margin-top: 30px;
      padding: 20px;
      border-radius: 10px;
      background: #f8f9fa;

      .result-header {
        margin-bottom: 15px;

        h3 {
          color: #2c3e50;
          margin: 0;
          font-size: 1.3rem;
          font-weight: 600;
        }
      }

      .result-content {
        &.AC {
          background: rgba(40, 167, 69, 0.1);
          border: 1px solid rgba(40, 167, 69, 0.3);
        }

        &.WA {
          background: rgba(220, 53, 69, 0.1);
          border: 1px solid rgba(220, 53, 69, 0.3);
        }

        .result-status {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 15px;
          font-weight: 600;
          font-size: 1.1rem;

          .el-icon {
            font-size: 1.2rem;
          }
        }

        .result-details {
          p {
            margin: 8px 0;
            color: #34495e;
            font-size: 1rem;
            word-break: break-word;
          }
          
          .score-details {
            font-weight: 600;
            color: #2c3e50;
            background: rgba(0, 123, 255, 0.1);
            padding: 8px 12px;
            border-radius: 6px;
            border-left: 4px solid #007bff;
          }
          
          .match-details {
            margin-top: 15px;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            
            h4 {
              margin: 0 0 10px 0;
              color: #495057;
              font-size: 1rem;
              font-weight: 600;
            }
            
            .keyword-list {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;
              margin-bottom: 12px;
              
              .keyword-item {
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 0.9rem;
                font-weight: 500;
                
                &.match-correct {
                  background: rgba(40, 167, 69, 0.1);
                  color: #28a745;
                  border: 1px solid rgba(40, 167, 69, 0.3);
                }
                
                &.match-partial {
                  background: rgba(255, 193, 7, 0.1);
                  color: #ffc107;
                  border: 1px solid rgba(255, 193, 7, 0.3);
                }
                
                &.match-missing {
                  background: rgba(220, 53, 69, 0.1);
                  color: #dc3545;
                  border: 1px solid rgba(220, 53, 69, 0.3);
                }
              }
            }
            
            .match-legend {
              display: flex;
              gap: 15px;
              font-size: 0.85rem;
              color: #6c757d;
              
              .legend-item {
                display: flex;
                align-items: center;
                gap: 4px;
                
                .legend-icon {
                  font-weight: bold;
                  
                  &.match-correct {
                    color: #28a745;
                  }
                  
                  &.match-partial {
                    color: #ffc107;
                  }
                  
                  &.match-missing {
                    color: #dc3545;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

/* 输入输出格式样式 */
.input-format-section,
.output-format-section {
  margin: 20px 0;
}

.input-format-section h4,
.output-format-section h4 {
  color: #409eff;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 600;
}

.format-content {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 15px;
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  color: #495057;
  overflow-x: auto;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  p {
    margin-top: 20px;
    color: #666;
    font-size: 1.1rem;
  }
}
</style>
